<template>
  <div class="template-management tech-page">
    <!-- 模型表单对话框 -->
    <ModelFormDialog
      v-model:visible="dialogVisible"
      :edit-data="currentModel"
      @refresh="fetchModelList"
    />
    <dv-border-box-12 class="tech-header-box">
      <div class="tech-header">
        <h2 class="tech-title">模型管理</h2>
        <el-button type="primary" class="tech-button tech-button--primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增模型
        </el-button>
      </div>
    </dv-border-box-12>

    <dv-border-box-8 class="tech-search-box">
      <div class="tech-search-bar">
        <el-form :inline="true" :model="searchForm" class="tech-search-form">

          <el-form-item label="模型名称">
            <el-input v-model="searchForm.name" placeholder="请输入模型名称" clearable />
          </el-form-item>
          <el-form-item label="状态" class="status-form-item">
            <el-select 
              v-model="searchForm.enableStatus" 
              placeholder="请选择状态" 
              clearable 
              class="tech-select"
              popper-class="tech-select-dropdown"
            >
              <el-option 
                label="启用" 
                value="enabled"
                class="tech-select-option"
              >
                <div class="status-option">
                  <span class="status-dot status-dot--enabled"></span>
                  <span>启用</span>
                </div>
              </el-option>
              <el-option 
                label="禁用" 
                value="disabled"
                class="tech-select-option"
              >
                <div class="status-option">
                  <span class="status-dot status-dot--disabled"></span>
                  <span>禁用</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="tech-button tech-button--primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button class="tech-button" @click="resetSearch">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </dv-border-box-8>

    <dv-border-box-10 class="tech-table-box">
      <div class="tech-table-container">
        <el-table
          v-loading="loading"
          :data="modelList"
          style="width: 100%"
          class="tech-table"
          element-loading-text="数据加载中..."
          element-loading-background="rgba(0, 20, 40, 0.8)"
        >
          <el-table-column prop="_id" label="模型ID" min-width="220" show-overflow-tooltip />
          <el-table-column prop="name" label="模型名称" min-width="150" show-overflow-tooltip />
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag 
                :type="scope.row.enable === false ? 'danger' : 'success'" 
                effect="dark"
                size="small"
              >
                {{ scope.row.enable === false ? '禁用' : '启用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" class="tech-button tech-button--primary" @click="handleEdit(scope.row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button 
                :type="scope.row.enable === false ? 'success' : 'warning'" 
                size="small" 
                class="tech-button" 
                :class="scope.row.enable === false ? 'tech-button--success' : 'tech-button--warning'"
                @click="handleToggleStatus(scope.row)"
              >
                <el-icon>
                  <Check v-if="scope.row.enable === false" />
                  <Close v-else />
                </el-icon>
                {{ scope.row.enable === false ? '启用' : '禁用' }}
              </el-button>
              <el-button type="danger" size="small" class="tech-button tech-button--danger" @click="handleDelete(scope.row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="tech-pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            prev-text="上一页"
            next-text="下一页"
            :pager-count="7"
          >
            <template #total>
              共 {{ total }} 条记录
            </template>
            <template #sizes>
              每页 {{ pageSize }} 条
            </template>
          </el-pagination>
        </div>
      </div>
    </dv-border-box-10>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete, Check, Close } from '@element-plus/icons-vue'
import { app, ensureLogin } from '../../utils/cloudbase'
import ModelFormDialog from '../../components/resume/ModelFormDialog.vue'

export default {
  name: 'TemplateManagement',
  components: {
    Plus,
    Search,
    Refresh,
    Edit,
    Delete,
    Check,
    Close,
    ModelFormDialog
  },
  setup() {
    // 搜索表单
    const searchForm = reactive({
      id: '',
      name: '',
      enableStatus: ''
    })

    // 表格数据
    const loading = ref(false)
    const modelList = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    // 初始化数据
    onMounted(() => {
      fetchModelList()
    })

    // 获取模型列表
    const fetchModelList = async () => {
      loading.value = true
      try {
        // 确保用户已登录
        await ensureLogin()
        
        // 构建查询参数
        const queryParams = {
          page: currentPage.value,
          pageSize: pageSize.value
        }
        
        // 添加搜索条件
        if (searchForm.id) {
          queryParams._id = searchForm.id
        }
        if (searchForm.name) {
          queryParams.name = searchForm.name
        }
        if (searchForm.enableStatus) {
          if (searchForm.enableStatus === 'enabled') {
            queryParams.enable = true
          } else if (searchForm.enableStatus === 'disabled') {
            queryParams.enable = false
          }
        }
        
        console.log('搜索参数:', queryParams)
        
        // 调用云函数
        let res;
        try {
          res = await app.callFunction({
            name: 'admin-resume-model-crud',
            data: {
              action: 'list',
              data: queryParams
            }
          });
        } catch (callError) {
          console.error('调用云函数失败:', callError);
          res = { result: { code: -1, message: '调用云函数失败' } };
        }
        
        const result = res.result || {}
        
        if (result.code === 0) {
          modelList.value = result.data.list || []
          total.value = result.data.total || 0
        } else {
          ElMessage.error(result.message || '获取模型列表失败')
          modelList.value = []
          total.value = 0
        }
      } catch (error) {
        console.error('获取模型列表失败:', error)
        ElMessage.error('获取模型列表失败')
        modelList.value = []
        total.value = 0
      } finally {
        loading.value = false
      }
    }

    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      fetchModelList()
    }

    // 重置搜索
    const resetSearch = () => {
      searchForm.id = ''
      searchForm.name = ''
      searchForm.enableStatus = ''
      handleSearch()
    }

    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchModelList()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchModelList()
    }

    // 对话框相关
    const dialogVisible = ref(false)
    const currentModel = ref(null)

    // 新增模型
    const handleAdd = () => {
      currentModel.value = null
      dialogVisible.value = true
    }

    // 编辑模型
    const handleEdit = (row) => {
      currentModel.value = { ...row }
      dialogVisible.value = true
    }

    // 删除模型
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除模型 "${row.name}" 吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          try {
            // 确保用户已登录
            await ensureLogin()
            
            // 调用云函数删除模型
            const res = await app.callFunction({
              name: 'admin-resume-model-crud',
              data: {
                action: 'delete',
                data: {
                  _id: row._id
                }
              }
            })
            
            if (res.result && res.result.code === 0) {
              ElMessage.success('删除成功')
              fetchModelList()
            } else {
              ElMessage.error(res.result?.message || '删除失败')
            }
          } catch (error) {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
          }
        })
        .catch(() => {
          // 用户取消删除
        })
    }

    // 切换模型启用/禁用状态
    const handleToggleStatus = async (row) => {
      const newStatus = row.enable === false
      const statusText = newStatus ? '启用' : '禁用'
      
      ElMessageBox.confirm(
        `确定${statusText}模型 "${row.name}" 吗？`,
        `${statusText}确认`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: newStatus ? 'success' : 'warning',
          customClass: 'datav-message-box',
          distinguishCancelAndClose: true,
          draggable: true,
          center: true,
          roundButton: true
        }
      )
        .then(async () => {
          loading.value = true
          try {
            const result = await app.callFunction({
              name: 'admin-resume-model-crud',
              data: {
                action: 'update',
                data: {
                  _id: row._id,
                  enable: newStatus
                }
              }
            })

            if (result.result && result.result.code === 0) {
              ElMessage.success(`${statusText}成功`)
              fetchModelList()
            } else {
              ElMessage.error(result.result?.message || `${statusText}失败`)
            }
          } catch (error) {
            console.error(`${statusText}模型失败:`, error)
            ElMessage.error(`${statusText}模型失败`)
          } finally {
            loading.value = false
          }
        })
        .catch(() => {
          // 取消操作
        })
    }

    return {
      searchForm,
      loading,
      modelList,
      currentPage,
      pageSize,
      total,
      dialogVisible,
      currentModel,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      handleDelete,
      handleToggleStatus,
      fetchModelList  // 导出 fetchModelList 函数，使其可以被 @refresh 事件调用
    }
  }
}
</script>

<style>
/* DataV 风格的消息弹窗样式 */
.datav-message-box {
  background-color: rgba(0, 19, 47, 0.9) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.3) !important;
  border-radius: 4px !important;
  backdrop-filter: blur(5px);
}

.datav-message-box .el-message-box__header {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-bottom: 1px solid rgba(0, 192, 255, 0.3) !important;
  padding: 15px 20px !important;
}

.datav-message-box .el-message-box__title {
  color: #00c0ff !important;
  font-weight: bold !important;
}

.datav-message-box .el-message-box__headerbtn .el-message-box__close {
  color: #00c0ff !important;
}

.datav-message-box .el-message-box__content {
  background-color: rgba(0, 19, 47, 0.8) !important;
  padding: 20px !important;
  color: #ffffff !important;
}

.datav-message-box .el-message-box__container {
  color: #ffffff !important;
}

.datav-message-box .el-message-box__status {
  color: #ff9900 !important;
  font-size: 24px !important;
}

.datav-message-box .el-message-box__message p {
  color: #ffffff !important;
  font-size: 16px !important;
}

.datav-message-box .el-message-box__footer {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-top: 1px solid rgba(0, 192, 255, 0.3) !important;
  padding: 10px 20px !important;
}

.datav-message-box .el-button.el-button--default {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border-color: rgba(0, 192, 255, 0.3) !important;
  color: rgba(0, 192, 255, 0.8) !important;
}

.datav-message-box .el-button.el-button--default:hover {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-color: rgba(0, 192, 255, 0.7) !important;
  color: #ffffff !important;
}

:deep(.datav-message-box .el-button.el-button--primary) {
  background-color: rgba(0, 192, 255, 0.2) !important;
  border-color: rgba(0, 192, 255, 0.7) !important;
  color: #00c0ff !important;
}

:deep(.datav-message-box .el-button.el-button--primary:hover) {
  background-color: rgba(0, 192, 255, 0.4) !important;
  border-color: #00c0ff !important;
  color: #ffffff !important;
  box-shadow: 0 0 10px rgba(0, 192, 255, 0.5) !important;
}
</style>

<style scoped>
.template-management {
  padding: 0;
}

/* 全局样式 */
.el-form-item {
  margin-bottom: 18px;
  margin-right: 20px;
}

.el-form-item__label {
  color: rgba(0, 192, 255, 0.9) !important;
  font-weight: 500;
  padding-right: 8px;
}

.el-form-item :deep(.el-input) {
  width: 160px;
}

.status-form-item {
  min-width: 160px;
}

.tech-select {
  width: 100%;
  min-width: 120px;
  background-color: rgba(0, 30, 60, 0.6);
  border-color: rgba(0, 192, 255, 0.5);
  color: #ffffff;
}

.tech-select :deep(.el-input__wrapper) {
  background-color: rgba(0, 30, 60, 0.6);
  box-shadow: 0 0 0 1px rgba(0, 192, 255, 0.5) inset !important;
  padding: 0 10px;
  height: 36px;
  border-radius: 4px;
  transition: all 0.3s;
  width: 100%;
}

.tech-select :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px rgba(0, 192, 255, 0.8) inset, 0 0 8px rgba(0, 192, 255, 0.3);
}

.tech-select :deep(.el-input__inner) {
  color: #ffffff;
  font-size: 14px;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tech-select :deep(.el-input__suffix) {
  color: rgba(0, 192, 255, 0.8);
}

.tech-select :deep(.el-select__caret) {
  color: rgba(0, 192, 255, 0.8);
  font-size: 16px;
}

/* 下拉菜单样式 */
:deep(.tech-select-dropdown) {
  background-color: rgba(0, 19, 47, 0.95) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.3) !important;
  border-radius: 4px !important;
  backdrop-filter: blur(5px);
  padding: 5px;
}

:deep(.tech-select-dropdown .el-select-dropdown__item) {
  color: #ffffff;
  background-color: transparent;
}

:deep(.tech-select-dropdown .el-select-dropdown__item.hover) {
  background-color: rgba(0, 192, 255, 0.2);
}

:deep(.tech-select-dropdown .el-select-dropdown__item.selected) {
  color: #00c0ff;
  font-weight: bold;
  background-color: rgba(0, 192, 255, 0.1);
}

/* 状态选项样式 */
.status-option {
  display: flex;
  align-items: center;
  padding: 2px 0;
  width: 100%;
}

.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 8px;
}

.status-dot--enabled {
  background-color: #67c23a;
  box-shadow: 0 0 5px rgba(103, 194, 58, 0.8);
}

.status-dot--disabled {
  background-color: #f56c6c;
  box-shadow: 0 0 5px rgba(245, 108, 108, 0.8);
}

/* 选中后的显示样式 */
.tech-select :deep(.el-select__tags) {
  background-color: transparent;
}

.tech-select :deep(.el-tag) {
  background-color: rgba(0, 192, 255, 0.15);
  border-color: rgba(0, 192, 255, 0.5);
  color: #ffffff;
  border-radius: 3px;
}

.tech-select :deep(.el-tag .el-tag__close) {
  color: rgba(255, 255, 255, 0.7);
  background-color: transparent;
}

.tech-select :deep(.el-tag .el-tag__close:hover) {
  background-color: rgba(0, 192, 255, 0.3);
  color: #ffffff;
}

.tech-button--success {
  background-color: rgba(0, 128, 0, 0.2);
  border-color: rgba(0, 192, 0, 0.7);
  color: #00c000;
}

.tech-button--success:hover {
  background-color: rgba(0, 128, 0, 0.4);
  border-color: #00c000;
  color: #ffffff;
  box-shadow: 0 0 10px rgba(0, 192, 0, 0.5);
}

.tech-button--warning {
  background-color: rgba(255, 153, 0, 0.2);
  border-color: rgba(255, 153, 0, 0.7);
  color: #ff9900;
}

.tech-button--warning:hover {
  background-color: rgba(255, 153, 0, 0.4);
  border-color: #ff9900;
  color: #ffffff;
  box-shadow: 0 0 10px rgba(255, 153, 0, 0.5);
}
</style>
